<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\SystemConfig\Logic;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Str;
use MoChat\Plugin\SystemConfig\Contract\SystemConfigContract;

class OemInfoLogic
{
    /**
     * @Inject
     * @var SystemConfigContract
     */
    protected $systemConfigService;

    public function handle(): array
    {
        // OEM信息配置
        $defaultOemInfo = [
            'siteTitle' => env('SYSTEM_CONFIG_SITE_TITLE',''),
            'loginLogo' => '',
            'copyrightName' => '由优墨科技提供技术支持',
            'copyrightUrl' => 'https://',
            'ico' => '',
            'brandName' => env('SYSTEM_CONFIG_BRAND_NAME',''),
            'miniLogo' => '',
            'customerServiceQrcode' => 'https://',
            'rightTitle' => env('SYSTEM_CONFIG_SITE_TITLE',''),
            'rightVersion' => '商业版',
            'rightDescription' => env('SYSTEM_CONFIG_SITE_TITLE',''),
        ];

        $oemInfo = $this->getOemConfig();
        if (empty($oemInfo)) {
            return $defaultOemInfo;
        }

        $oemInfo = array_column($oemInfo, 'value', 'name');
        $newOemInfo = [];
        foreach ($oemInfo as $key => $oem) {
            $key = str_replace('oem.', '', $key);
            $key = Str::camel($key);
            $newOemInfo[$key] = $oem;
            if (empty($oem) && ! empty($defaultOemInfo[$key])) {
                $newOemInfo[$key] = $defaultOemInfo[$key];
            }
        }

        return $newOemInfo;
    }

    protected function getOemConfig(): array
    {
        $names = ['oem.domain', 'oem.site_title', 'oem.site_keyword', 'oem.site_description', 'oem.dashboard_url', 'oem.api_url', 'oem.sidebar_url', 'oem.operation_url', 'oem.brand_name', 'oem.login_logo', 'oem.mini_logo', 'oem.customer_service_qrcode', 'oem.right_title', 'oem.right_version', 'oem.right_description', 'oem.copyright_name', 'oem.copyright_url', 'oem.icp', 'oem.ico'];
        return $this->getConfigValues($names);
    }

    protected function getConfigValues($names): array
    {
        $config = $this->systemConfigService->getSystemConfigsByName($names, ['id', 'name']);
        foreach ($config as $k => $v) {
            $config[$k]['value'] = '';
            $configValue = $this->systemConfigService->getSystemConfigValueByConfigId($v['id'], ['value']);
            if (! empty($configValue)) {
                $config[$k]['value'] = $configValue['value'];
            }

            if (! empty($configValue) && in_array($config[$k]['name'], ['oem.login_logo', 'oem.mini_logo', 'oem.ico', 'oem.customer_service_qrcode'])) {
                $config[$k]['value'] = file_full_url((string) $configValue['value']);
            }
        }
        return $config;
    }
}
